import { dictUrl } from '../../../../api/index'
import { entryInfoUrl, entrySaveUrl, userInfoUrl, userUpdateeInfoUrl } from '../../../../api/individual'
import { post, get, uploadFile, initUploadFileListKey } from '../../../../utils/index'
import areaList from '../../../../assets/js/areaData'
import WxValidate from '../../../../utils/WxValidate'

Page({
  data: {
    page: '',
    readonly: false,
    form: {},
    formError: {},
    householdLocationPopup: false,
    householdTypePopup: false,
    householdLocationColumns: [],
    householdTypeColumns: [],
    maritalColumns: [],
    cardAddressPopup: false,
    areaList: areaList,
    photoList: [],
    residencePermitList: [],
    unemploymentCertificateList: []
  },
  async submit () { // 保存信息
    const { form, page } = this.data
    if (!this.WxValidate.checkForm(form)) {
      const formError = this.WxValidate.formError
      this.setData({ formError })
      wx.showToast({ title: '信息填写有误，请检查', icon: 'none' })
      return
    }
    const url = page === 'entry' ? entrySaveUrl : userUpdateeInfoUrl
    this.setData({ formError: {} })
    await post(url, form)
    wx.navigateBack({})
  },
  async loadData () { // 获取人员信息
    const url = this.data.page === 'entry' ? entryInfoUrl : userInfoUrl
    let [photoList, residencePermitList, unemploymentCertificateList] = [[], [], []]
    const { data } = await post(url)
    if (data.photoAddress) {
      photoList = [{ url: data.photoAddress, name: '个人照片' }]
    }
    if (data.residencePermit && data.residencePermit.link) {
      const residencePermit = initUploadFileListKey(data.residencePermit)
      residencePermitList = [residencePermit]
    }
    if (data.unemploymentCertificate && data.unemploymentCertificate.link) {
      const unemploymentCertificate = initUploadFileListKey(data.unemploymentCertificate)
      unemploymentCertificateList = [unemploymentCertificate]
    }

    if (data.cardAddressCityId) {
      const { areaList: { province_list, city_list, county_list } } = this.data
      const { cardAddressProvinceId, cardAddressCityId, cardAddressCountyId } = data
      data.cardAddress = `${province_list[cardAddressProvinceId]}-${city_list[cardAddressCityId]}-${county_list[cardAddressCountyId]}`
    }
    data.genderName = data.gender && data.gender.dictValue
    data.nationName = data.nation && data.nation.dictValue
    data.householdLocationName = data.householdLocation && data.householdLocation.dictValue
    data.householdTypeName = data.householdType && data.householdType.dictValue
    data.maritalName = data.marital && data.marital.dictValue
    this.setData({ form: data, photoList, residencePermitList, unemploymentCertificateList })
  },
  async loadHouseholdLocation () { // 户口所在地字典
    const { data } = await get(dictUrl, { code: 'householdLocation' })
    this.setData({ householdLocationColumns: data })
  },
  async loadHouseholdType () { // 户口性质字典
    const { data } = await get(dictUrl, { code: 'householdType' })
    this.setData({ householdTypeColumns: data })
  },
  async loadMarital () { // 婚姻状况字典
    const { data } = await get(dictUrl, { code: 'marital' })
    this.setData({ maritalColumns: data })
  },
  cardAddressDetailChange ({ detail }) { // 身份证住址
    this.setData({ 'form.cardAddressDetail': detail })
  },
  cardAddressClick () { // 身份证住址弹窗
    if (this.data.readonly) {
      return
    }
    wx.hideKeyboard()
    this.setData({ cardAddressPopup: true })
  },
  cardAddressClose () { // 身份证住址取消
    this.setData({ cardAddressPopup: false })
  },
  cardAddressConfirm ({ detail }) { // 身份证住址确认
    const { values } = detail
    this.setData({
      'form.cardAddressProvinceId': values[0].code,
      'form.cardAddressCityId': values[1].code,
      'form.cardAddressCountyId': values[2].code,
      'form.cardAddress': `${values[0].name}-${values[1].name}-${values[2].name}`
    })
    this.cardAddressClose()
  },
  householdLocationClick () { // 户口所在地弹窗
    if (this.data.page !== 'entry') {
      wx.showToast({ title: '变更户籍地请到首页的业务办理', icon: 'none' })
      return
    }
    wx.hideKeyboard()
    this.setData({ householdLocationPopup: true })
  },
  householdLocationClose () { // 户口所在地取消
    this.setData({ householdLocationPopup: false })
  },
  householdLocationConfirm ({ detail }) { // 户口所在地确认
    const { value } = detail
    this.setData({
      'form.householdLocationCode': value.dictKey,
      'form.householdLocationName': value.dictValue
    })
    this.householdLocationClose()
  },
  householdTypeClick () { // 户口性质弹窗
    if (this.data.readonly) {
      return
    }
    wx.hideKeyboard()
    this.setData({ householdTypePopup: true })
  },
  householdTypeClose () { // 户口性质取消
    this.setData({ householdTypePopup: false })
  },
  householdTypeConfirm ({ detail }) { // 户口性质确认
    const { value } = detail
    this.setData({
      'form.householdTypeCode': value.dictKey,
      'form.householdTypeName': value.dictValue
    })
    this.householdTypeClose()
  },
  maritalClick () { // 婚姻状况弹窗
    if (this.data.readonly) {
      return
    }
    wx.hideKeyboard()
    this.setData({ maritalPopup: true })
  },
  maritalClose () { // 婚姻状况取消
    this.setData({ maritalPopup: false })
  },
  maritalConfirm ({ detail }) { // 婚姻状况确认
    const { value } = detail
    this.setData({
      'form.maritalCode': value.dictKey,
      'form.maritalName': value.dictValue
    })
    this.maritalClose()
  },
  permanentAddressDetailChange ({ detail }) { // 常住详细地址
    this.setData({ 'form.permanentAddressDetail': detail })
  },
  emailChange ({ detail }) { // 邮箱
    this.setData({ 'form.email': detail })
  },
  async photoRead ({ detail }) { // 一寸照上传
    const { file } = detail
    let { data } = await uploadFile(file.path)
    data = initUploadFileListKey(data)
    this.setData({ photoList: [data] })
    this.data.form.photo = data.link
    this.data.form.photoId = data.id
  },
  photoDel () { // 一寸照删除
    this.data.form.photo = ''
    this.data.form.photoId = ''
    this.setData({ photoList: [] })
  },
  async residencePermitRead ({ detail }) { // 居住证复印件(外地)上传
    const { file } = detail
    let { data } = await uploadFile(file.path)
    data = initUploadFileListKey(data)
    this.data.form.residencePermit = data
    this.data.form.residencePermitId = data.id
    this.setData({ residencePermitList: [data] })
  },
  residencePermitDel () { // 居住证复印件(外地)删除
    this.data.form.residencePermit = {}
    this.data.form.residencePermitId = ''
    this.setData({ residencePermitList: [] })
  },
  residencePermitPreview ({ detail }) { // 居住证复印件(外地)预览
    const { index } = detail
    const file = this.data.residencePermitList[index]
    if (!file || file.isImage) {
      return
    }
    wx.openDocument({ filePath: file.url })
  },
  async unemploymentCertificateRead ({ detail }) { // 就业创业失业证复印件上传
    const { file } = detail
    let { data } = await uploadFile(file.path)
    data = initUploadFileListKey(data)
    this.data.form.unemploymentCertificate = data
    this.data.form.unemploymentCertificateId = data.id
    this.setData({ unemploymentCertificateList: [data] })
  },
  unemploymentCertificateDel () { // 就业创业失业证复印件删除
    this.data.form.unemploymentCertificate = {}
    this.data.form.unemploymentCertificateId = ''
    this.setData({ unemploymentCertificateList: [] })
  },
  unemploymentCertificatePreview ({ detail }) { // 就业创业失业证复印件预览
    const { index } = detail
    const file = this.data.unemploymentCertificateList[index]
    if (!file || file.isImage) {
      return
    }
    wx.openDocument({ filePath: file.url })
  },
  initValidator () { // 初始化验证器
    const rules = {
      cardAddressDetail: { required: true },
      cardAddressCityId: { required: true },
      householdLocationCode: { required: true },
      householdTypeCode: { required: true },
      maritalCode: { required: true },
      permanentAddressDetail: { required: true },
      email: { email: true },
      // photoId: { required: true }
    }
    const messages = {
      cardAddressDetail: { required: '请输入身份证住址' },
      cardAddressCityId: { required: '请选择现身份证地址' },
      householdLocationCode: { required: '请选择户口所在地' },
      householdTypeCode: { required: '请选择户口性质' },
      maritalCode: { required: '请选择婚姻状况' },
      permanentAddressDetail: { required: '有效送达地址（家庭地址）' },
      email: { email: '请填写正确邮箱' },
      // photoId: { required: '请上传个人照片' },
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  readonlyChange () { // 编辑资料
    this.setData({ readonly: false })
  },
  onLoad (options) {
    // page表示从哪个页面过来的, entry->入职； change->修改；me->我的
    const { page } = options
    const readonly = page === 'me'
    this.setData({ readonly, page })
    this.loadData()
    this.loadHouseholdLocation()
    this.loadHouseholdType()
    this.loadMarital()
    this.initValidator()
  }
})